package com.excellence.intercepter;

import com.alibaba.fastjson.JSONObject;
import com.excellence.datamodel.Result;
import com.excellence.utils.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;


/**
 * @author 徐瑞琪
 */
@Slf4j
@Component
public class RequestInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //登录前
        String url = request.getRequestURL().toString();
        log.info("请求路径为:{}", url);
        if (url.contains("login")||url.contains("/user/insertSelective")) {
            return true;
        }
        //查看令牌是否存在
        String jwt = request.getHeader("token");
        if (!StringUtils.hasLength(jwt)) {
            //返回401
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            String notLogin = JSONObject.toJSONString(Result.error(401, "not login！"));
            response.getWriter().write(notLogin);
            return false;
        }
        //解析令牌
        try {
            JwtUtil.parseToken(jwt);
        } catch (Exception e) {
            e.printStackTrace();
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            String notLogin = JSONObject.toJSONString(Result.error(401, "未登录!"));
            response.getWriter().write(notLogin);
            return false;
        }
        return true;
    }
}
